package com.chengyu.core.service.walk.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.domain.enums.TrendsEnums;
import com.chengyu.core.domain.form.TrendsForm;
import com.chengyu.core.domain.form.WalkTrendsBatchAdd;
import com.chengyu.core.domain.result.WalkTrendsCommentResult;
import com.chengyu.core.domain.result.WalkTrendsGoodsResult;
import com.chengyu.core.domain.result.WalkTrendsResult;
import com.chengyu.core.entity.CommonPage;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.mapper.*;
import com.chengyu.core.model.*;
import com.chengyu.core.service.goods.GoodsService;
import com.chengyu.core.service.member.WeixinNoticeService;
import com.chengyu.core.service.system.QiniuService;
import com.chengyu.core.service.walk.WalkMemberCollectService;
import com.chengyu.core.service.walk.WalkTrendsService;
import com.chengyu.core.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WalkTrendsServiceImpl implements WalkTrendsService {

    @Autowired
    private WalkTrendsBatchMapper walkTrendsBatchMapper;
    @Autowired
    private WalkTrendsMapper trendsMapper;
    @Autowired
    private WalkTrendsCollectionMapper trendsCollectionMapper;
    @Autowired
    private WalkTrendsCommentMapper trendsCommentMapper;
    @Autowired
    private BaseMapper baseMapper;
    @Autowired
    private WalkTrendsGoodsMapper walkTrendsGoodsMapper;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private WalkTrendsCommentLikeMapper trendsCommentLikeMapper;
    @Autowired
    private WalkMemberCollectService walkMemberCollectService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private WeixinNoticeService weixinNoticeService;
    @Autowired
    private UmsMemberMapper umsMemberMapper;
    @Autowired
    private PmsGoodsMapper goodsMapper;
    @Autowired
    private RecommendGoodsMapper recommendGoodsMapper;
    @Autowired
    private UmsShopOwnLevelMapper umsShopOwnLevelMapper;
    @Autowired
    private UmsShopLevelUseLogMapper umsShopLevelUseLogMapper;
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void publishTrends(WalkMember walkMember, WalkTrends trends, List<Integer> goodsIdList) throws ServiceException {
        trends.setWalkMemberId(walkMember.getId());
        trends.setWalkMemberName(walkMember.getNickname());
        trends.setWalkMemberHeadImg(walkMember.getHeadImg());
        trends.setWalkMemberUid(walkMember.getUid());
        trends.setSort(9999);
        trends.setWeight(0);
        trends.setViewNum(0);
        trends.setCollectionNum(0);
        trends.setCommentNum(0);
        trends.setGoodsId(goodsIdList.get(0));
        trends.setLocation(trends.getLocation());
        trends.setBelongMemberId(0);
        //获取平台的参数
        SysConfigExample example = new SysConfigExample();
        example.createCriteria().andNidEqualTo("shop_upload_examine");
        List<SysConfig> sysConfigList = sysConfigMapper.selectByExample(example);
        if (sysConfigList.get(0).getValue().equals("1")) {
            trends.setStatus(CommonConstant.WAIT_INT);
        } else {
            trends.setStatus(CommonConstant.SUS_INT);
        }


        trends.setAddTime(DateUtil.date());
        trends.setUpdTime(trends.getAddTime());
        trendsMapper.insertSelective(trends);

        this.addTrendsGoods(trends, goodsIdList);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void publishTrendsBatch(WalkMember walkMember, List<WalkTrendsBatchAdd> trendsList, Integer shopId) throws ServiceException {
        //检查商家的会员上传是否有还够用
        //数量
        UmsShopOwnLevelExample exampleOwnLevel = new UmsShopOwnLevelExample();
        UmsShopOwnLevelExample.Criteria criteria = exampleOwnLevel.createCriteria();
        criteria.andShopIdEqualTo(shopId);
        List<Integer> types = new ArrayList<>();
        types.add(1);
        types.add(3);
        criteria.andTypeIn(types);
        criteria.andDeadlineGreaterThan(new Date());
        List<UmsShopOwnLevel> umsShopOwnLevels = umsShopOwnLevelMapper.selectByExample(exampleOwnLevel);
        Integer totalNum = 0;
        for (UmsShopOwnLevel umsShopOwnLevel : umsShopOwnLevels) {
            totalNum = totalNum + umsShopOwnLevel.getResidueUploadTrendsNum();
        }
        if (totalNum == 0 || trendsList.size()>totalNum) {
            throw new ServiceException("商家会员剩余上传素材数量不足，当前剩余："+totalNum+"条");
        }


        Boolean videoFlag = false;
        Boolean imgFlag = false;
        String typeName = "";
        //获取平台的参数
        SysConfigExample example = new SysConfigExample();
        example.createCriteria().andNidEqualTo("shop_upload_examine");
        List<SysConfig> sysConfigList = sysConfigMapper.selectByExample(example);
        for (WalkTrendsBatchAdd trends : trendsList) {
            if (trends.getType() == 1) {
                videoFlag = true;
            }
            if (trends.getType() == 3) {
                imgFlag = true;
            }
            if (walkMember != null) {
                trends.setWalkMemberId(walkMember.getId());
                trends.setWalkMemberName(walkMember.getNickname());
                trends.setWalkMemberHeadImg(walkMember.getHeadImg());
                trends.setWalkMemberUid(walkMember.getUid());
            }

            trends.setSort(9999);
            trends.setWeight(0);
            trends.setViewNum(0);
            if (trends.getGoodsIdList() != null && trends.getGoodsIdList().size() > 0) {
                trends.setGoodsId(trends.getGoodsIdList().get(0));
            }
            trends.setCollectionNum(0);
            trends.setCommentNum(0);
            trends.setShopId(shopId);
            trends.setLocation(trends.getLocation());
            trends.setBelongMemberId(0);

            if (trends.getLocation() == 1) {
                if (sysConfigList.get(0).getValue().equals("1")) {
                    trends.setStatus(CommonConstant.WAIT_INT);
                } else {
                    trends.setStatus(CommonConstant.SUS_INT);
                }
            } else {
                trends.setStatus(CommonConstant.SUS_INT);
            }
            trends.setAddTime(DateUtil.date());
            trends.setUpdTime(trends.getAddTime());

//            if (trends.getType() == 1 && StringUtils.isBlank(trends.getVideoUrlWatermark())) {
//                //这里自己拼装水印地址，(这里暂时不用了，用前端得水印方法)
//                String waterUrl = trends.getVideoUrl().replace(CommonConstant.UPLOAD_PRE, CommonConstant.WATERMARK_PRE);
//                trends.setVideoUrlWatermark(waterUrl);
//            } else if (trends.getType() == 3 && StringUtils.isBlank(trends.getImagesUrlWatermark())) {
//                String waterUrl = trends.getImages().replace(CommonConstant.UPLOAD_PRE, CommonConstant.WATERMARK_PRE);
//                trends.setImagesUrlWatermark(waterUrl);
//            }

//            List<Integer> goodsIdList = trends.getGoodsIdList();
//            this.addTrendsGoods(trends, goodsIdList);//(素材和商品1对1 这里就不用添加中间表了)


        }
        walkTrendsBatchMapper.insertBatch(trendsList);


        //添加成功后，扣减此商家的剩余上传次数
        Integer currentTotalDataNum = trendsList.size();
        for (UmsShopOwnLevel umsShopOwnLevel : umsShopOwnLevels) {
            if (umsShopOwnLevel.getResidueUploadTrendsNum() <= currentTotalDataNum) {
                //如何这条拥有数量小于上传数量直接扣减掉
                UmsShopOwnLevel umsShopOwnLevelUpdate = new UmsShopOwnLevel();
                umsShopOwnLevelUpdate.setResidueUploadTrendsNum(0);
                umsShopOwnLevelUpdate.setId(umsShopOwnLevel.getId());
                umsShopOwnLevelMapper.updateByPrimaryKeySelective(umsShopOwnLevelUpdate);
                currentTotalDataNum = currentTotalDataNum - umsShopOwnLevel.getResidueUploadTrendsNum();
            } else if (umsShopOwnLevel.getResidueUploadTrendsNum() > currentTotalDataNum) {
                UmsShopOwnLevel umsShopOwnLevelUpdate = new UmsShopOwnLevel();
                umsShopOwnLevelUpdate.setResidueUploadTrendsNum(umsShopOwnLevel.getResidueUploadTrendsNum() - currentTotalDataNum);
                umsShopOwnLevelUpdate.setId(umsShopOwnLevel.getId());
                umsShopOwnLevelMapper.updateByPrimaryKeySelective(umsShopOwnLevelUpdate);
            }
        }
        //添加会员等级使用记录-素材发布
        for (WalkTrendsBatchAdd walkTrendsBatchAdd : trendsList) {
            UmsShopLevelUseLog umsShopLevelUseLog = new UmsShopLevelUseLog();
            umsShopLevelUseLog.setShopId(shopId);
            umsShopLevelUseLog.setType(1);
            umsShopLevelUseLog.setNum(1.0);
            umsShopLevelUseLog.setTrendsId(walkTrendsBatchAdd.getId());
            umsShopLevelUseLog.setAddTime(new Date());
            umsShopLevelUseLogMapper.insert(umsShopLevelUseLog);
        }


        if (videoFlag && !imgFlag) {
            typeName = "视频";
        } else if (!videoFlag && imgFlag) {
            typeName = "图片";
        } else {
            typeName = "视频/图片";
        }
        //发送微信模板消息
        //查看他的所属子用户列表
        if (walkMember != null) {
            UmsMemberExample umsMemberExample = new UmsMemberExample();
            umsMemberExample.createCriteria().andShopMemberIdEqualTo(walkMember.getMemberId());
            List<UmsMember> umsMembers = umsMemberMapper.selectByExample(umsMemberExample);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(trendsList.get(0).getAddTime());
            for (UmsMember umsMember : umsMembers) {
                weixinNoticeService.trendsPublishNotice(umsMember.getId(), time, walkMember.getShopName(), String.valueOf(trendsList.size()), typeName);
            }
        }

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void editTrends(WalkTrends trends, List<Integer> goodsIdList) {
        trends.setUpdTime(DateUtil.date());
        trendsMapper.updateByPrimaryKeySelective(trends);

        WalkTrendsGoodsExample example = new WalkTrendsGoodsExample();
        example.createCriteria().andTrendsIdEqualTo(trends.getId());
        walkTrendsGoodsMapper.deleteByExample(example);

        this.addTrendsGoods(trends, goodsIdList);
    }

    @Override
    public void editTrendsContent(WalkTrends trends) throws ServiceException {
        trendsMapper.updateByPrimaryKeySelective(trends);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void editTrendsNoGoods(WalkTrends trends) {
        trends.setUpdTime(DateUtil.date());
        trendsMapper.updateByPrimaryKeySelective(trends);
    }

    private void addTrendsGoods(WalkTrends trends, List<Integer> goodsIdList) {
        if (CollectionUtil.isNotEmpty(goodsIdList)) {
            StringBuilder goodsImgs = new StringBuilder();
            for (Integer goodsId : goodsIdList) {
                WalkTrendsGoods walkTrendsGoods = new WalkTrendsGoods();
                walkTrendsGoods.setTrendsId(trends.getId());
                PmsGoods goods = goodsService.getGoods(goodsId);
                walkTrendsGoods.setGoodsId(goods.getId());
                walkTrendsGoods.setGoodsName(goods.getTitle());
                walkTrendsGoods.setGoodsMainImg(goods.getMainImg());
                walkTrendsGoods.setPrice(goods.getPrice());
                walkTrendsGoods.setAddTime(trends.getAddTime());
                walkTrendsGoods.setUpdTime(trends.getAddTime());
                walkTrendsGoodsMapper.insertSelective(walkTrendsGoods);
                goodsImgs.append("|" + goods.getMainImg());
            }
            if (trends.getType() == TrendsEnums.TrendsType.GOODS.getValue()) {
                //宝贝上新将宝贝主图插入到images
                WalkTrends updateTrends = new WalkTrends();
                updateTrends.setId(trends.getId());
                updateTrends.setImages(goodsImgs.substring(1));
                trendsMapper.updateByPrimaryKeySelective(updateTrends);
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void verifyTrends(Integer id, Integer status, String reason) {
        WalkTrends trends = new WalkTrends();
        trends.setId(id);
        trends.setStatus(status);
        trends.setVerifyTime(DateUtil.date());
        trends.setReason(reason);
        trendsMapper.updateByPrimaryKeySelective(trends);
    }

    @Override
    public CommonPage<WalkTrendsResult> getTrendsList(List<Integer> showLocation, Integer location, Boolean isAll, Integer goodsId, Boolean isRefreshGetNumber, TrendsForm form, Integer page, Integer pageSize) {

        if (form.getIsShowInGg() == null) {
            form.setIsShowInGg(false);
        }
        WalkTrendsExample example = new WalkTrendsExample();
        if (StringUtils.isNotBlank(form.getSort())) {
            example.setOrderByClause(form.getSort());
        } else {
            example.setOrderByClause("add_time desc");
        }
        if (goodsId != null && isRefreshGetNumber != null && isRefreshGetNumber && !form.getIsShowInGg()) {
            example.setOrderByClause("RAND()");
        }
        WalkTrendsExample.Criteria criteria = example.createCriteria();
        if (form.getShopId() != null) {
            criteria.andShopIdEqualTo(form.getShopId());
        }
        if (form.getDownLoadStatus() != null) {
            if (form.getDownLoadStatus() == 0) {
                criteria.andBelongMemberIdEqualTo(0);
            } else {
                criteria.andBelongMemberIdNotEqualTo(0);
            }
        }
        if (form.getWalkMemberUid() != null) {
            criteria.andWalkMemberUidEqualTo(form.getWalkMemberUid());
        }
        if (form.getType() != null) {
            criteria.andTypeEqualTo(form.getType());
        }
        if (CollectionUtil.isNotEmpty(form.getTypeList())) {
            criteria.andTypeIn(form.getTypeList());
        }
        if (form.getStatus() != null) {
            criteria.andStatusEqualTo(form.getStatus());
        }
        if (form.getFirstTrendsId() != null) {
            criteria.andIdNotEqualTo(form.getFirstTrendsId());
        }
        if (form.getIsShowInGg() != null && form.getIsShowInGg()) {
            criteria.andIsShowInGgEqualTo(form.getIsShowInGg());
        }

        if (form.getOnlyOneTrendsId() != null) {
            criteria.andIdEqualTo(form.getOnlyOneTrendsId());
        }

        if (location != null) {
            criteria.andLocationEqualTo(location);
        }


        if (!isAll) {
            criteria.andBelongMemberIdEqualTo(0);
        }
        if (showLocation != null && showLocation.size() != 0) {
            criteria.andLocationIn(showLocation);
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        if (goodsId != null && isRefreshGetNumber != null && isRefreshGetNumber && !form.getIsShowInGg()) {
            criteria.andGoodsIdEqualTo(goodsId);
            pageSize = 3;
        }
        PageHelper.startPage(page, pageSize);
        List<WalkTrends> list = trendsMapper.selectByExampleWithBLOBs(example);

        List<WalkTrendsResult> trendsList = new ArrayList<>();
        if (page == 1 && form.getFirstTrendsId() != null) {
            WalkTrendsResult walkTrendsResult = this.getTrendsDetail(form.getFirstTrendsId());
            if (walkTrendsResult != null && walkTrendsResult.getWalkTrends() != null) {
                walkTrendsResult.setCollectTrends(this.isCollection(form.getWalkMember(), form.getFirstTrendsId()));
                walkTrendsResult.setCollectWalkMember(walkMemberCollectService.isCollectWalkMember(form.getWalkMember(), walkTrendsResult.getWalkTrends().getWalkMemberId()));
                trendsList.add(walkTrendsResult);
            }
        }

        for (WalkTrends walkTrends : list) {
            WalkTrendsResult walkTrendsResult = new WalkTrendsResult();
            walkTrendsResult.setWalkTrends(walkTrends);
            walkTrendsResult.setCollectTrends(this.isCollection(form.getWalkMember(), walkTrends.getId()));
//            walkTrendsResult.setCollectWalkMember(walkMemberCollectService.isCollectWalkMember(form.getWalkMember(), walkTrends.getWalkMemberId()));
            PmsGoods goods = new PmsGoods();
            if (walkTrends.getGoodsId() != null) {
                goods = goodsService.getGoods(walkTrends.getGoodsId());
                if (goods == null) {
                    continue;
                }
                List<WalkTrendsGoods> walkTrendsGoodsList = new ArrayList<>();
                WalkTrendsGoodsResult walkTrendsGoodsResult = new WalkTrendsGoodsResult();
                walkTrendsGoodsResult.setGoodsId(goods.getId());
                walkTrendsGoodsResult.setTrendsId(walkTrends.getId());
                walkTrendsGoodsResult.setGoodsName(goods.getTitle());
                walkTrendsGoodsResult.setGoodsMainImg(goods.getMainImg());
                walkTrendsGoodsResult.setPrice(goods.getPrice());
                //查看这个视频是否在平台推荐里面
                RecommendGoodsExample exampleRecommendGoods = new RecommendGoodsExample();
                exampleRecommendGoods.createCriteria().andGoodsIdEqualTo(goods.getId());
                List<RecommendGoods> recommendGoodsList = recommendGoodsMapper.selectByExample(exampleRecommendGoods);
                if (recommendGoodsList.size() > 0) {
                    walkTrendsGoodsResult.setRecommend(true);
                }

                walkTrendsGoodsList.add(walkTrendsGoodsResult);
                walkTrendsResult.setTrendsGoodsList(walkTrendsGoodsList);
            }

            trendsList.add(walkTrendsResult);
        }
//        List<?> walkTrendsResultAfterRandom;
//        if (goodsId != null && isRefreshGetNumber != null && isRefreshGetNumber && !form.getIsShowInGg()) {
//            walkTrendsResultAfterRandom = NumberUtils.getListRandomObj(trendsList, 3);
//        } else {
//            walkTrendsResultAfterRandom = trendsList;
//        }
        PageInfo pageInfo = new PageInfo<>(list);
        pageInfo.setList(trendsList);
        return CommonPage.restPage(pageInfo);
    }

    @Override
    public List<WalkTrendsResult> getTrendsListForAi(Integer location, Boolean isAll, String showIds, Integer goodsId, Boolean isRefreshGetNumber, TrendsForm form, Integer page, Integer pageSize) {
        String[] showIdsArray = new String[]{};
        if (showIds.contains("[")) {
            if (StringUtils.isNotBlank(showIds)) {
                showIdsArray = showIds.substring(1, showIds.length() - 1).split(",");
            }
        } else {
            showIdsArray = showIds.split(",");
        }


        List<String> showIdsList = Arrays.asList(showIdsArray);
        List<Integer> showIdsListInt = new ArrayList<>();
        for (String s : showIdsList) {
            if (StringUtils.isNotBlank(s)) {
                showIdsListInt.add(Integer.parseInt(s));
            }

        }

        WalkTrendsExample example = new WalkTrendsExample();

        example.setOrderByClause("RAND() limit 1");

        WalkTrendsExample.Criteria criteria = example.createCriteria();
        if (form.getWalkMemberId() != null) {
            criteria.andWalkMemberIdEqualTo(form.getWalkMemberId());
        }
        if (form.getWalkMemberUid() != null) {
            criteria.andWalkMemberUidEqualTo(form.getWalkMemberUid());
        }
        if (form.getType() != null) {
            criteria.andTypeEqualTo(form.getType());
        }
        if (CollectionUtil.isNotEmpty(form.getTypeList())) {
            criteria.andTypeIn(form.getTypeList());
        }
        if (form.getStatus() != null) {
            criteria.andStatusEqualTo(form.getStatus());
        }
        if (location != null) {
            criteria.andLocationEqualTo(location);
        }
        if (form.getFirstTrendsId() != null) {
            criteria.andIdNotEqualTo(form.getFirstTrendsId());
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        if (showIdsListInt.size() > 0) {
            criteria.andIdNotIn(showIdsListInt);
        }


        if (!isAll) {
            criteria.andBelongMemberIdEqualTo(0);
        }

        List<WalkTrends> walkTrends = trendsMapper.selectByExampleWithBLOBs(example);

        List<WalkTrendsResult> trendsList = new ArrayList<>();
        for (WalkTrends walkTrendsItem : walkTrends) {
            WalkTrendsResult walkTrendsResult = new WalkTrendsResult();
            walkTrendsResult.setWalkTrends(walkTrendsItem);
            walkTrendsResult.setCollectTrends(this.isCollection(form.getWalkMember(), walkTrendsItem.getId()));
//            walkTrendsResult.setCollectWalkMember(walkMemberCollectService.isCollectWalkMember(form.getWalkMember(), walkTrendsItem.getWalkMemberId()));
            WalkTrendsGoodsExample goodsExample = new WalkTrendsGoodsExample();
            goodsExample.createCriteria().andTrendsIdEqualTo(walkTrendsItem.getId());
            walkTrendsResult.setTrendsGoodsList(walkTrendsGoodsMapper.selectByExample(goodsExample));
            trendsList.add(walkTrendsResult);
        }
        return trendsList;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteTrends(String ids) {
        List<String> idsList = Arrays.asList(ids.split(CommonConstant.DH_REGEX));
        List<Integer> trendsIdList = Convert.convert(new TypeReference<List<Integer>>() {
        }, idsList);

        WalkTrendsExample example = new WalkTrendsExample();
        example.createCriteria().andIdIn(trendsIdList);
        trendsMapper.deleteByExample(example);

        //删除关注
        WalkTrendsCollectionExample collectionExample = new WalkTrendsCollectionExample();
        collectionExample.createCriteria().andTrendsIdIn(trendsIdList);
        trendsCollectionMapper.deleteByExample(collectionExample);

        //删除评论
        WalkTrendsCommentExample commentExample = new WalkTrendsCommentExample();
        commentExample.createCriteria().andTrendsIdIn(trendsIdList);
        trendsCommentMapper.deleteByExample(commentExample);
        //删除对应的商品
        WalkTrendsGoodsExample goodsExample = new WalkTrendsGoodsExample();
        goodsExample.createCriteria().andTrendsIdIn(trendsIdList);
        walkTrendsGoodsMapper.deleteByExample(goodsExample);

    }

    @Override
    public boolean isCollection(WalkMember viewMember, Integer trendId) {
        if (viewMember == null) {
            return false;
        }
        WalkTrendsCollectionExample example = new WalkTrendsCollectionExample();
        example.createCriteria().andViewMemberIdEqualTo(viewMember.getId()).andTrendsIdEqualTo(trendId);
        long num = trendsCollectionMapper.countByExample(example);
        return num > 0;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void collectOrCancelTrends(WalkMember viewMember, Integer trendsId) {
        WalkTrends trends = trendsMapper.selectByPrimaryKey(trendsId);
        if (this.isCollection(viewMember, trendsId)) {
            //取消关注
            WalkTrendsCollectionExample example = new WalkTrendsCollectionExample();
            example.createCriteria().andViewMemberIdEqualTo(viewMember.getId()).andTrendsIdEqualTo(trendsId);
            trendsCollectionMapper.deleteByExample(example);

            //关注人数-1
            baseMapper.update("update walk_trends set collection_num = collection_num-1 where id = " + trendsId);
            baseMapper.update("update walk_member set like_num = like_num-1 where id = " + trends.getWalkMemberId());
        } else {
            //关注
            WalkTrendsCollection collection = new WalkTrendsCollection();
            collection.setViewMemberId(viewMember.getId());
            collection.setViewMemberName(viewMember.getNickname());
            collection.setViewMemberHeadImg(viewMember.getHeadImg());
            collection.setWalkMemberId(trends.getWalkMemberId());
            collection.setWalkMemberName(trends.getWalkMemberName());
            collection.setWalkMemberHeadImg(trends.getWalkMemberHeadImg());
            collection.setTrendsId(trends.getId());
            collection.setTrendsContent(trends.getContent());
            collection.setTrendsImages(trends.getImages());
            collection.setTrendsVideoUrl(trends.getVideoUrl());
            collection.setAddTime(DateUtil.date());
            collection.setUpdTime(collection.getAddTime());
            collection.setShopId(trends.getShopId());
            trendsCollectionMapper.insertSelective(collection);

            //关注人数+1
            baseMapper.update("update walk_trends set collection_num = collection_num+1 where id = " + trendsId);
            baseMapper.update("update walk_member set like_num = like_num+1 where id = " + trends.getWalkMemberId());
        }
    }

    @Override
    public List<WalkTrendsCollection> getMyCollectionTrends(Integer viewWalkMemberId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);

        WalkTrendsCollectionExample example = new WalkTrendsCollectionExample();
        example.setOrderByClause("add_time desc");
        example.createCriteria().andViewMemberIdEqualTo(viewWalkMemberId);
        return trendsCollectionMapper.selectByExample(example);
    }

    @Override
    public List<WalkTrendsCollection> getMyGetCollectionTrends(Integer walkMemberId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);

        WalkTrendsCollectionExample example = new WalkTrendsCollectionExample();
        example.setOrderByClause("add_time desc");
        example.createCriteria().andWalkMemberIdEqualTo(walkMemberId);
        return trendsCollectionMapper.selectByExample(example);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public WalkTrendsComment addComment(WalkMember viewMember, Integer trendsId, Integer commentId, String content) {
        WalkTrendsComment comment = new WalkTrendsComment();
        comment.setViewMemberId(viewMember.getId());
        comment.setViewMemberName(viewMember.getNickname());
        comment.setViewMemberHeadImg(viewMember.getHeadImg());
        comment.setTrendsId(trendsId);

        WalkTrends trends = trendsMapper.selectByPrimaryKey(trendsId);
        comment.setWalkMemberId(trends.getWalkMemberId());
        comment.setWalkMemberName(trends.getWalkMemberName());
        comment.setWalkMemberHeadImg(trends.getWalkMemberHeadImg());
        comment.setTrendsId(trends.getId());
        comment.setContent(content);
        comment.setStatus(CommonConstant.YES_INT);
        if (commentId != null) {
            comment.setType(2);
            comment.setPid(commentId);
            WalkTrendsComment parentComment = trendsCommentMapper.selectByPrimaryKey(commentId);
            if (parentComment.getTid() == null) {
                comment.setTid(parentComment.getId());
            } else {
                comment.setTid(parentComment.getTid());
            }
            comment.setContent("@" + parentComment.getViewMemberName() + " " + comment.getContent());
        } else {
            comment.setType(1);
        }
        comment.setAddTime(DateUtil.date());
        comment.setUpdTime(comment.getAddTime());
        trendsCommentMapper.insertSelective(comment);

        baseMapper.update("update walk_trends set comment_num=comment_num+1 where id = " + trendsId);
        return comment;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteComment(Integer commentId) {
        trendsCommentMapper.deleteByPrimaryKey(commentId);

        WalkTrendsCommentLikeExample example = new WalkTrendsCommentLikeExample();
        example.createCriteria().andCommentIdEqualTo(commentId);
        trendsCommentLikeMapper.deleteByExample(example);
    }

    @Override
    public boolean isLikeComment(WalkMember viewMember, Integer commentId) {
        if (viewMember == null) {
            return false;
        }
        WalkTrendsCommentLikeExample example = new WalkTrendsCommentLikeExample();
        example.createCriteria().andViewMemberIdEqualTo(viewMember.getId()).andCommentIdEqualTo(commentId);
        long num = trendsCommentLikeMapper.countByExample(example);
        return num > 0;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void likeOrCancelComment(WalkMember viewMember, Integer commentId) {
        if (this.isLikeComment(viewMember, commentId)) {
            //取消关注
            WalkTrendsCommentLikeExample example = new WalkTrendsCommentLikeExample();
            example.createCriteria().andViewMemberIdEqualTo(viewMember.getId()).andCommentIdEqualTo(commentId);
            trendsCommentLikeMapper.deleteByExample(example);

            //关注人数-1
            baseMapper.update("update walk_trends_comment set like_num = like_num-1 where id = " + commentId);
        } else {
            //关注
            WalkTrendsCommentLike commentLike = new WalkTrendsCommentLike();
            commentLike.setViewMemberId(viewMember.getId());
            commentLike.setViewMemberName(viewMember.getNickname());
            commentLike.setViewMemberHeadImg(viewMember.getHeadImg());
            commentLike.setCommentId(commentId);
            commentLike.setAddTime(DateUtil.date());
            commentLike.setUpdTime(commentLike.getAddTime());
            trendsCommentLikeMapper.insertSelective(commentLike);

            //关注人数+1
            baseMapper.update("update walk_trends_comment set like_num = like_num+1 where id = " + commentId);
        }
    }

    @Override
    public CommonPage<WalkTrendsCommentResult> getTrendsCommentList(Integer trendsId, WalkMember currentMember, Integer viewWalkMemberId, Integer walkMemberId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);

        WalkTrendsCommentExample example = new WalkTrendsCommentExample();
        example.setOrderByClause("add_time desc");
        WalkTrendsCommentExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(1);
        if (trendsId != null) {
            criteria.andTrendsIdEqualTo(trendsId);
        }
        if (viewWalkMemberId != null) {
            criteria.andViewMemberIdEqualTo(viewWalkMemberId);
        }
        if (walkMemberId != null) {
            criteria.andWalkMemberIdEqualTo(walkMemberId);
        }
        List<WalkTrendsComment> list = trendsCommentMapper.selectByExampleWithBLOBs(example);

        List<WalkTrendsCommentResult> commentList = new ArrayList<>();
        for (WalkTrendsComment walkTrendsComment : list) {
            walkTrendsComment.setLikeStatus(this.isLikeComment(currentMember, walkTrendsComment.getId()) ? 1 : 0);
            WalkTrendsCommentResult walkTrendsCommentResult = new WalkTrendsCommentResult();
            walkTrendsCommentResult.setWalkTrendsComment(walkTrendsComment);

            example = new WalkTrendsCommentExample();
            example.setOrderByClause("add_time desc");
            example.createCriteria().andTidEqualTo(walkTrendsComment.getId()).andTypeEqualTo(2);
            List<WalkTrendsComment> child = trendsCommentMapper.selectByExampleWithBLOBs(example);
            if (currentMember != null && CollectionUtil.isNotEmpty(child)) {
                for (WalkTrendsComment childComment : child) {
                    childComment.setLikeStatus(this.isLikeComment(currentMember, childComment.getId()) ? 1 : 0);
                }
            }
            walkTrendsCommentResult.setChilidCommentList(child);
            commentList.add(walkTrendsCommentResult);
        }

        PageInfo pageInfo = new PageInfo<>(list);
        pageInfo.setList(commentList);
        return CommonPage.restPage(pageInfo);
    }

    @Override
    public WalkTrends getTrendsById(Integer trendsId) {
        return trendsMapper.selectByPrimaryKey(trendsId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addViewNums(Integer trendsId, Integer num) {
        baseMapper.update("update walk_trends set view_num = view_num+" + num + " where id = " + trendsId);
    }

    @Override
    public WalkTrendsResult getTrendsDetail(Integer trendsId) {
        WalkTrendsResult result = new WalkTrendsResult();
        WalkTrends walkTrends = this.getTrendsById(trendsId);
        result.setWalkTrends(walkTrends);

        List<WalkTrendsGoods> walkTrendsGoodsList = new ArrayList<>();
        PmsGoods goods = goodsMapper.selectByPrimaryKey(walkTrends.getGoodsId());
        WalkTrendsGoods walkTrendsGoodsResult = new WalkTrendsGoods();
        walkTrendsGoodsResult.setGoodsId(goods.getId());
        walkTrendsGoodsResult.setTrendsId(walkTrends.getId());
        walkTrendsGoodsResult.setGoodsName(goods.getTitle());
        walkTrendsGoodsResult.setGoodsMainImg(goods.getMainImg());
        walkTrendsGoodsResult.setPrice(goods.getPrice());
        walkTrendsGoodsList.add(walkTrendsGoodsResult);
        result.setTrendsGoodsList(walkTrendsGoodsList);
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteCollectionTrends(WalkMember member, Integer trendsId) {
        WalkTrendsCollectionExample example = new WalkTrendsCollectionExample();
        example.createCriteria().andViewMemberIdEqualTo(member.getId()).andTrendsIdEqualTo(trendsId);
        trendsCollectionMapper.deleteByExample(example);
        baseMapper.update("update walk_trends set collection_num = collection_num-1 where id = " + trendsId);

    }

    @Override
    public void createWatermark(List<WalkTrends> trendsList) throws Exception {
        for (WalkTrends walkTrends : trendsList) {
            try {
                if (walkTrends.getType() == 3) {
                    String s = qiniuService.uploadByImgWithWatermark(walkTrends.getImages());
                    walkTrends.setImagesUrlWatermark(s);
                } else if (walkTrends.getType() == 1) {
                    String s = qiniuService.uploadByVideoWithWatermark(walkTrends.getVideoUrl());
                    walkTrends.setVideoUrlWatermark(s);
                }
            } catch (Exception e) {
                if (e.getMessage().contains("file exists")) {
                    throw new ServiceException("水印文件已经存在！");
                }
            }


            trendsMapper.updateByPrimaryKeySelective(walkTrends);
        }

    }

    @Override
    public void deleteTrendsByGoodsId(Integer goodsId) {
        WalkTrendsExample example = new WalkTrendsExample();
        example.createCriteria().andGoodsIdEqualTo(goodsId);
        trendsMapper.deleteByExample(example);
    }

    @Override
    public void deleteTrendsByDown() {
        WalkTrendsExample example = new WalkTrendsExample();
        example.createCriteria().andBelongMemberIdIsNotNull();
        trendsMapper.deleteByExample(example);
    }

    @Override
    public Integer getAllMaterialNum(Integer type, Integer shopId, Integer goodsId) {
        int i = walkTrendsBatchMapper.selectCountByType(type, shopId, goodsId);
        return i;
    }

}